<?php
/**
 * @link https://www.kancloud.cn/cleverstone/ymb2
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

namespace extend\kdniao\request;

use extend\kdniao\BaseRequest;
use extend\kdniao\Kdniao;
use yii\helpers\Json;

/**
 * 智能地址解析
 *
 * ```php
 *  //创建智能地址解析服务实例
 *  $intelligenceResolveAddress = IntelligenceResolveAddress::createObject();
 *  $intelligenceResolveAddress->setParamContent('河南省 郑州市 金水区 通信产业园100001号');
 *
 *  //创建快递鸟客户端
 *  $kdniao = Kdniao::createObject();
 *  $execState = $kdniao->setRequest($intelligenceResolveAddress)->execute();
 *  if ($execState) {
 *      return $kdniao->result;
 *  } else {
 *      return $kdniao->error;
 *  }
 *
 *  ```
 *
 * @author clevstn
 * @since ym2.0
 */
class IntelligenceResolveAddress extends BaseRequest
{
    //服务请求标识
    private $_requestUri = 'api/dist';
    //服务指令标识
    private $_requestType = '6001';
    //请求内容需进行URL(utf-8)编码。请求内容JSON格式，须和DataType一致。
    private $_requestData = [];
    //请求、返回数据类型：2-json；
    private $_dataType = '2';

    /**
     * @param string $content 设置要解析的内容
     * @return $this
     */
    public function setParamContent($content)
    {
        $this->_requestData['Content'] = (string)$content;
        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function getRequestUrl()
    {
        return self::API_DOMAIN . $this->_requestUri;
    }

    /**
     * {@inheritDoc}
     */
    public function getServiceName()
    {
        return '智能地址解析';
    }

    /**
     * {@inheritDoc}
     */
    public function getRequestParams()
    {
        $requestData = Json::encode($this->_requestData);
        return [
            'EBusinessID' => Kdniao::E_BUSINESS_ID,
            'RequestType' => $this->_requestType,
            'RequestData' => urlencode($requestData),
            'DataType' => $this->_dataType,
            'DataSign' => Kdniao::generateSign($requestData),
        ];
    }

    /**
     * {@inheritDoc}
     */
    public function triggerResponseCallback(Kdniao $kdniao)
    {
        //对接口结果进行判断处理。
        $processData = Json::decode($kdniao->result);
        if ($processData['Success'] && $processData['ResultCode'] == 100) {
            $kdniao->result = $processData['Data'];
        } else {
            $kdniao->error = $processData['Reason'] ?? '内容输入格式错误，解析结果为空！';
        }
    }
}